<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus, Search, Refresh } from "@element-plus/icons-vue";
import RoleForm from "./modules/roleForm.vue";
import AssignMenus from "./modules/assignMenus.vue";
import { getRoleList, deleteRole } from "@/api/role";
import type { Role } from "@/api/role";
import { formatDate } from "@/utils/format";

defineOptions({
  name: "RoleManagement"
});

// 表格数据
const tableData = ref<Role[]>([]);
const loading = ref(false);
const searchForm = reactive({
  keyword: ""
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 弹窗控制
const roleFormVisible = ref(false);
const assignMenusVisible = ref(false);
const formType = ref<"add" | "edit">("add");
const currentRole = ref<Partial<Role>>({});

// 获取角色列表
const getRoles = async () => {
  loading.value = true;
  try {
    const res = await getRoleList({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    });

    if (res.code === 0) {
      tableData.value = res.data.list;
      pagination.total = res.data.total;
    } else {
      ElMessage.error(res.msg || "获取角色列表失败");
    }
  } catch (error) {
    console.error("获取角色列表出错:", error);
    ElMessage.error("获取角色列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getRoles();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = "";
  pagination.currentPage = 1;
  getRoles();
};

// 打开弹窗
const openDialog = (type: "add" | "edit", row?: Role) => {
  formType.value = type;
  if (type === "add") {
    currentRole.value = {};
  } else {
    currentRole.value = { ...row };
  }
  roleFormVisible.value = true;
};

// 打开分配菜单弹窗
const openAssignMenusDialog = (row: Role) => {
  currentRole.value = { ...row };
  assignMenusVisible.value = true;
};

// 保存角色
const handleSaveRole = () => {
  roleFormVisible.value = false;
  getRoles(); // 重新加载列表
};

// 保存角色菜单
const handleSaveRoleMenus = () => {
  assignMenusVisible.value = false;
  getRoles(); // 重新加载列表
};

// 删除角色
const handleDeleteRole = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除该角色吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const res = await deleteRole(id);
    if (res.code === 0) {
      ElMessage.success("删除成功");
      getRoles();
    } else {
      ElMessage.error(res.msg || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除角色出错:", error);
      ElMessage.error("删除角色失败");
    }
  }
};

// 页码变更
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  getRoles();
};

// 每页数量变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getRoles();
};

// 格式化创建时间
const formatCreateTime = (time: number) => {
  if (!time) return '-';
  return formatDate(new Date(time * 1000), 'YYYY-MM-DD HH:mm:ss');
};

onMounted(() => {
  getRoles();
});
</script>

<template>
  <div>
    <!-- 搜索栏 -->
    <el-card class="search-container" shadow="never">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键字">
          <el-input v-model="searchForm.keyword" placeholder="角色名称/编码" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <el-button type="primary" :icon="Plus" @click="openDialog('add')">添加角色</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="code" label="角色编码" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="系统角色" width="90">
          <template #default="{ row }">
            <el-tag type="info" size="small" v-if="row.is_system === 1">系统角色</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160">
          <template #default="{ row }">
            {{ formatCreateTime(new Date(row.created_at).getTime() / 1000) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="button-group">
              <el-button type="primary" size="small" :icon="Edit" @click="openDialog('edit', row)">
                编辑
              </el-button>
              <el-button type="success" size="small" @click="openAssignMenusDialog(row)">
                分配菜单
              </el-button>
              <el-button type="danger" size="small" :icon="Delete" @click="handleDeleteRole(row.id)"
                :disabled="row.is_system === 1">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 角色表单 -->
    <RoleForm v-model:visible="roleFormVisible" :role="currentRole" :type="formType" @save="handleSaveRole" />

    <!-- 分配菜单 -->
    <AssignMenus v-model:visible="assignMenusVisible" :role="currentRole" @save="handleSaveRoleMenus" />
  </div>
</template>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: end;
  margin-top: 20px;
}

.mx-1 {
  margin-right: 5px;
}

.button-group {
  display: flex;
  gap: 8px;
}
</style>